// pages/search/search.js
const http = require('../../utils/http');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotArray: [], //搜索建议
    inputState: false, //input焦点
    searchData: [], //搜索后数据
    historyArr: [],//历史搜索
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getHotData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.shelFun()
  },


  // 热门搜索建议
  getHotData() {
    http.get('search/getHotWords').then(res => {
      // console.log('搜索建议---->', res.list);
      this.setData({
        hotArray: res.list
      })
    })
  },
  // 获取焦点
  inputFocus(event) {
    console.log(event);
    // this.setData({
    //   inputState:true
    // })
  },
  // 失去焦点
  inputBlur(event) {
    console.log(event);
    // this.setData({
    //   inputState:false
    // })
  },
  inputKey(event) {
    this.dataShelFun(event.detail.value)
    console.log(event.detail.value);
    // 
    http.get("/search/book.json", {
      keyword: event.detail.value
    }).then(res => {
      // console.log(res);
      app.globalData.searchArray = res
      app.globalData.searchNovel = event.detail.value
      // console.log(app.globalData.searchArray);
      this.setData({
        inputState: true,
        searchData: res
      })
    })

  },
  // 搜索记录
  // 添加到书架
  dataShelFun(k) {
    // novel_mine_id
    if (!app.globalData.userInfo) {
      const shelCollect = wx.cloud.database().collection("novel_search_txt");
      // 是否存在 id
      shelCollect.where({
        txt: k
      }).get().then(res => {
        if (res.data.length > 0) {
          shelCollect.where({
            txt: k
          }).remove().then(res => {
            console.log('删除成功');
          });
        } else {
          shelCollect.add({
            data: {
              txt: k,
              coltime: new Date().getTime()
            }
          }).then(res => {
            console.log('添加成功');
          })
        }
      })
    }
  },
  // 初始化
  shelFun() {
    if (!app.globalData.userInfo) {
      const fun = wx.cloud.database().collection("novel_search_txt");
      fun.get().then(res => {
        console.log(res.data);
        this.setData({
          historyArr: res.data
        })
      })
    }
  },
  // 清除历史记录
  delFun() {
    const db = wx.cloud.database();
    const _ = db.command;
    const del = db.collection("novel_search_txt");
    del.where({
      coltime: _.lt(new Date().getTime())
    }).remove().then(res => {
      wx.showToast({
        title: 'success',
        title: '删除成功'
      })
      this.setData({
        historyArr: []
      })
    })
  },
  // 
})